package com.enation.app.javashop.framework.context;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;


@Configuration
public class RestConfig {

    @Autowired
    private RestTemplateBuilder builder;

    /**
     * 默认 只支持服务内访问 只能通过注册中心转发
     */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = builder.build();
        restTemplate.setRequestFactory(this.getDefaultFactory());
        return restTemplate;
    }


    /**
     * 服务内访问 只能通过注册中心转发
     */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplateIn() {
        RestTemplate restTemplate = builder.build();
        restTemplate.setRequestFactory(this.getDefaultFactory());
        return restTemplate;
    }


    /**
     * 服务外访问(无负载) 支持自定义URL访问
     */
    @Bean
    public RestTemplate restTemplateOut() {
        RestTemplate restTemplate = builder.build();
        restTemplate.setRequestFactory(this.getDefaultFactory());
        return restTemplate;
    }


    /**
     * 获取默认配置工厂
     */
    private ClientHttpRequestFactory getDefaultFactory(){
        return this.getCustomFactory(60 * 1000, 60 * 1000);
    }


    /**
     * 自定义配置工厂
     */
    private ClientHttpRequestFactory getCustomFactory(int connectTimeout, int readTimeout){
        // 配置连接工厂
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(connectTimeout);
        requestFactory.setReadTimeout(readTimeout);
        return requestFactory;
    }

}
